package com.zzh.core.dao.impl;

import com.zzh.core.base.BaseSpringJdbcDao;
import com.zzh.core.dao.StudentDao;
import com.zzh.core.model.Student;
import java.util.List;
import org.springframework.dao.support.DataAccessUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.stereotype.Repository;

@Repository
public class StudentDaoImpl extends BaseSpringJdbcDao<Student, Integer> implements StudentDao {

  @Override
  public Class getEntityClass() {
    return Student.class;
  }

  @Override
  public String getIdentifierPropertyName() {
    return "id";
  }

  public String getSelectPrefix() {
    return "select  "
        + " id as id,"
        + " name as name,"
        + " phone as phone,"
        + " ctime as ctime,"
        + " mtime as mtime,"
        + " deleted as deleted"
        + " from student ";
  }

  @Override
  public String getFindByIdSql() {
    return getSelectPrefix() + " where id = ?";
  }

  @Override
  public String getDeleteByIdSql() {
    return "delete from student where id = ?";
  }

  @Override
  public Student save(Student entity) {
    String sql = "insert into student "
        + " (id,name,phone,ctime,mtime,deleted) "
        + " values "
        + " (:id,:name,:phone,:ctime,:mtime,:deleted)";
    insertWithIdentity(entity, sql);
    return entity;
  }

  @Override
  public int update(Student entity) {
    String sql = "UPDATE student SET "
        + " id=:id,name=:name,phone=:phone,ctime=:ctime,mtime=:mtime,deleted=:deleted "
        + " WHERE id=:id";
    return getNamedParameterJdbcTemplate().update(sql, new BeanPropertySqlParameterSource(entity));
  }

  @Override
  public Student findOne(Integer id) {
    List<Student> result = getJdbcTemplate()
        .query(getFindByIdSql(), new Object[]{id}, new BeanPropertyRowMapper(getEntityClass()));
    return DataAccessUtils.singleResult(result);
  }

  @Override
  public void delete(Integer id) {
    getJdbcTemplate().update(getDeleteByIdSql(), id);
  }

  @Override
  public Page<Student> page(Pageable pageable, Student student) {
    String sql = getSelectPrefix() + " where 1=1 " +
        "/~ and id = [id] ~/" +
        "/~ and name = '[name]' ~/" +
        "/~ and phone = [phone] ~/" +
        "/~ and ctime = [ctime] ~/" +
        "/~ and mtime = [mtime] ~/" +
        "/~ and deleted = [deleted] ~/";
    return pageQuery(sql, pageable, new BeanPropertyRowMapper(getEntityClass()), student);
  }
}